package com.cheer.controller;

import com.cheer.service.MallOrderService;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author cheer
 */
@RestController
@RequestMapping("/pay")
@Slf4j
public class MallPayController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private MallOrderService mallOrderService;

    @ApiOperation(value = "支付回调通知处理")
    @PostMapping("/notify")
    public String parseOrderNotifyResult(@RequestBody String xmlData) throws WxPayException {
        try {
            final WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            if (StringUtils.isNotBlank(notifyResult.getOutTradeNo())){
                mallOrderService.paySuccessByNumber(notifyResult.getOutTradeNo());
            }
            return WxPayNotifyResponse.success("成功");
        } catch (Exception e) {
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }
}
